<script setup lang="ts">
import type { StudentUploadDto } from "@/api/student/type";
import { ElMessage } from 'element-plus';
import { ref, computed, onMounted, reactive } from "vue";
//引入学生相关的小仓库
import useStudentStore from '@/store/modules/student';
import { parseJwt } from "@/utils/token";
// 新增：用于追踪文件上传状态
let fileUploaded = ref(false);
const isNextButtonDisabled = ref(false); // 按钮是否禁用
const nextButtonText = ref('进入下一阶段'); // 按钮文本

const isBackButtonDisabled = ref(true); // 按钮是否禁用

let studentStore = useStudentStore();
// 计算属性用于转换 groupFinish 的值
const finishStatusMap = computed(() => {
  return {
    0: '未开始',
    1: '需求分析进行中',
    2: '概要设计进行中',
    3: '详细设计',
    4: '软件编码',
    5: '测试',
    6: '完成'
  };
});
// 辅助函数用于获取完成进度描述
const getFinishStatus = (status: number): string => {
  // @ts-ignore
  return finishStatusMap.value[status] || '未知状态';
};
// 新增计算属性用于判断上传按钮是否可见
const isUploadButtonVisible = computed(() => {
  return studentStore.groupInfo.groupIsAvailable === 1 && !isFnished.value;
});

let project = reactive({ name: 'project', role: '组长', step: '开始' });
const goNext = async () => {
  if (studentStore.userInfo.studentFinish >= studentStore.groupInfo.groupFinish) {
    ElMessage.warning('当前进度快于小组进度，不可进入');
    return;
  }
  if (!fileUploaded.value) {
    ElMessage.warning('请先提交文件');
    return;
  }

  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    console.log("学生Id为：", claims.studentId);
    await studentStore.studentEnterNext(claims.studentId);
    if (studentStore.userInfo.studentFinish != 0) {
      isBackButtonDisabled.value = false;
    }
    // 如果已经是最后一个阶段，则禁用按钮并更改文本
    if (studentStore.userInfo.studentFinish === 6) {
      project.step = getFinishStatus(studentStore.userInfo.studentFinish);
      isNextButtonDisabled.value = true;
      isFnished.value = true;
      nextButtonText.value = '完成';
      ElMessage.success('所有阶段已完成');
    } else {
      fileUploaded.value = false; // 更新状态，表示现在需要重新提交文件
      project.step = getFinishStatus(studentStore.userInfo.studentFinish);
      ElMessage.success('已进入下一阶段，请准备新的文件上传');
    }
  } else {
    project.step = getFinishStatus(studentStore.userInfo.studentFinish);
    ElMessage.error('未登录');
  }
}

const goBack = async () => {


  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    console.log("学生Id为：", claims.studentId);
    await studentStore.studentGoBack(claims.studentId);
    //如果不是最后一个阶段
    if (studentStore.groupInfo.groupFinish != 6) {
      nextButtonText.value = '进入下一阶段';
      isNextButtonDisabled.value = false;
      isFnished.value = false;
    }

    // 如果已经是最后一个阶段，则禁用按钮并更改文本
    if (studentStore.userInfo.studentFinish === 0) {
      project.step = getFinishStatus(studentStore.userInfo.studentFinish);
      isBackButtonDisabled.value = true;
      ElMessage.success('回到上一阶段成功，已回到最初阶段');
    } else {
      isBackButtonDisabled.value = false;
      project.step = getFinishStatus(studentStore.userInfo.studentFinish);
      ElMessage.success('回到上一阶段成功');
    }
  } else {
    project.step = getFinishStatus(studentStore.userInfo.studentFinish);
    ElMessage.error('未登录');
  }
}
const handleUpload = async (uploadRequestOptions: any) => {
  const file = uploadRequestOptions.file;
  if (studentStore.token != null) {

    let claims = parseJwt(studentStore.token);
    const data: StudentUploadDto = {
      file,
      studentId: claims.studentId
    };
    console.log("学生Id为：", data.studentId);
    try {
      console.log("data:", data);
      await studentStore.uploadFile(data);
      fileUploaded.value = true; // 标记文件已成功上传
      ElMessage.success('文件上传成功');
    } catch (error) {
      ElMessage.error('文件上传失败');
      // 错误已经通过 ElMessage 显示，这里可以进行其他处理
    }
  }
  else {
    ElMessage.error('未登录');
  }
}
onMounted(async () => {
  project.step = getFinishStatus(studentStore.userInfo.studentFinish)
  if (studentStore.userInfo.studentFinish != 0) {
    isBackButtonDisabled.value = false;
  }
  if (studentStore.userInfo.studentFinish === 6) {
    isNextButtonDisabled.value = true;
    isFnished.value = true;
    nextButtonText.value = '完成';
  }
  project.name = studentStore.userInfo.groupProName;
  if (studentStore.userInfo.studentPosition == 1) {
    project.role = "组长";
  }
  else if (studentStore.userInfo.studentPosition == 0) {
    project.role = "组员";
  }
  else {
    project.role = "未加入小组";
  }
  // 显示项目相关信息
  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    console.log("学生Id为：", claims.studentId);
    console.log("data:", claims.studentId);
    await studentStore.studentGetGroup(claims.studentId);
  }
});

const dialogVisible = ref(false);
let isSubmitting = ref(false);
const createForm = reactive({
  projectName: '',
  groupName: '',
});
// 创建项目和小组的方法
const createProjectAndGroup = () => {
  // 在这里实现创建项目和小组的逻辑
  dialogVisible.value = true; // 关闭对话框
  console.log('创建项目和小组');
};
const dialogJoinVisible = ref(false);
const proDialogVisible = ref(false);
interface group {
  groupId: number;
  studentId: number;
  groupName: string;
  groupProName: string;
  groupScore: number;
  groupIsAvailable: number;
  groupLeader: string;
  groupNotice: string;
  groupFinish: number;
  classId: number;
  giteeUrl: string;
}
// 定义一个函数来转换数据格式
const transformData = (groupList: group[]): { value: number; label: string }[] => {
  return groupList.map(item => ({
    value: item.groupId, // 使用class_id作为value
    label: item.groupName // 使用class_name作为label
  }));
};
const availableGroups = computed(() => {
  return transformData(studentStore.tableClassGroupData);
});
const openPro = () => {
  proDialogVisible.value = true;
}

const openJoin = async () => {
  dialogJoinVisible.value = true;
  //执行一个查询班级小组的逻辑
  if (studentStore.token != null) {

    let claims = parseJwt(studentStore.token);

    console.log("学生Id为：", claims.classId);
    try {
      await studentStore.getClassGroups(claims.classId);
      console.log("获取班级小组的信息成功的");
    } catch (error) {
      ElMessage.error('文件上传失败');
      // 错误已经通过 ElMessage 显示，这里可以进行其他处理
    }
  }
  else {
    ElMessage.error('未登录');
  }
}

const submitFormPro = async () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;
  // 禁用提交按钮，并使用类型断言
  const submitButton = document.querySelector('.dialog-footer .el-button--primary') as HTMLButtonElement;
  if (submitButton) {
    submitButton.disabled = true;
  }
  try {
    console.log('提交的表单数据:', createForm);
    await studentStore.createPro({
      groupName: studentStore.groupInfo.groupName,
      groupProName: createForm.projectName
    });
    ElMessage.success("创建项目成功");
    if (studentStore.token != null) {
      let claims = parseJwt(studentStore.token);
      await studentStore.fetchStudentInfo(claims.studentId);

      project.name = studentStore.userInfo.groupProName;
      if (studentStore.userInfo.studentPosition == 1) {
        project.role = "组长";
      }
      else if (studentStore.userInfo.studentPosition == 0) {
        project.role = "组员";
      }
      else {
        project.role = "未加入小组";
      }
      project.step = getFinishStatus(studentStore.userInfo.studentFinish)

    } else {
      console.log("仓库里面没有这个人的token");
    }
  } catch (error) {
    console.error("Failed to fetch user info or create group", error);
    ElMessage.error("创建小组失败");
  } finally {
    isSubmitting.value = false;
    if (submitButton) {
      submitButton.disabled = false;
    }
    proDialogVisible.value = false;
  }
};

const submitForm = async () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;
  // 禁用提交按钮，并使用类型断言
  const submitButton = document.querySelector('.dialog-footer .el-button--primary') as HTMLButtonElement;
  if (submitButton) {
    submitButton.disabled = true;
  }
  try {
    console.log('提交的表单数据:', createForm);
    await studentStore.createGroup({
      groupName: createForm.groupName,
      groupProName: '未创建项目'
    });
    //在重新获取小组的信息
    if (studentStore.token != null) {
      let claims = parseJwt(studentStore.token);
      await studentStore.fetchStudentInfo(claims.studentId);
      await studentStore.studentGetGroup(claims.studentId);
      project.name = studentStore.userInfo.groupProName;
      if (studentStore.userInfo.studentPosition == 1) {
        project.role = "组长";
      }
      else if (studentStore.userInfo.studentPosition == 0) {
        project.role = "组员";
      }
      else {
        project.role = "未加入小组";
      }
      project.step = getFinishStatus(studentStore.userInfo.studentFinish);

      ElMessage.success("创建小组成功");
    } else {
      console.log("仓库里面没有这个人的token");
    }
  } catch (error) {
    console.error("Failed to fetch user info or create group", error);
    ElMessage.error("创建小组失败");
  } finally {
    isSubmitting.value = false;
    if (submitButton) {
      submitButton.disabled = false;
    }
    dialogVisible.value = false;
  }
};
// 加入小组表单数据
const joinForm = ref({
  groupId: '',
  reason: ''
});
// 提交加入小组表单
const submitJoinForm = async () => {
  console.log('提交加入小组:', joinForm.value);
  console.log('申请的理由：', joinForm.value.reason);
  if (studentStore.token != null) {
    let claims = parseJwt(studentStore.token);
    // 准备请求数据
    const data = {
      groupId: joinForm.value.groupId,
      studentApplyReason: joinForm.value.reason,
      studentId: claims.studentId
    };
    await studentStore.applyEnterGroup(data);
    dialogJoinVisible.value = false;
  } else {
    console.log("仓库里面没有这个人的token");
  }
}

// 假设你已经从后端获取了 leader 和 username
const leader = ref<string>(studentStore.groupInfo.groupLeader); // 小组领导者的用户名
const username = ref<string>(studentStore.userInfo.studentName); // 当前用户的用户名

// 计算属性：判断当前用户是否是小组的领导者
const isLeader = computed(() => leader.value === username.value);
const isFnished = ref<boolean>(false);

// 新增：计算属性用于判断小组是否可用
const isGroupAvailable = computed(() => {
  return studentStore.groupInfo.groupIsAvailable === 1;
});
</script>
<template>
  <el-card>
    <!-- 使用 template #header 插槽定义卡片头部 -->
    <template #header>
      <!-- 新增一行用于放置"创建项目和小组"按钮 -->
      <!-- 新增一个带边框的容器来包裹按钮 -->
      <div class="header-button-container">
        <el-row type="flex" justify="end">
          <!-- 根据 leader 和 username 判断是否显示按钮 -->
          <el-button v-if="!isLeader" type="primary" @click="openJoin">加入小组</el-button>
          <el-button v-if="!isLeader" type="primary" @click="createProjectAndGroup">创建小组</el-button>
          <el-button v-if="isLeader" type="primary" @click="openPro">创建或修改项目</el-button>
        </el-row>
      </div>
      <!-- 加入小组的对话框 -->
      <el-dialog v-model="dialogJoinVisible" title="加入小组" width="30%" center>
        <el-form :model="joinForm" label-width="100px">
          <!-- 班级选择器 -->
          <el-form-item prop="groupId" label="小组名">
            <el-select v-model="joinForm.groupId" class="m-2" placeholder="请选择小组">
              <el-option v-for="item in availableGroups" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="申请理由">
            <el-input type="textarea" v-model="joinForm.reason" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogJoinVisible = false">取消</el-button>
            <el-button type="primary" @click="submitJoinForm">提交</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 原有的项目名和成员身份行 -->
      <el-row :gutter="20" justify="space-between">
        <el-col :span="4">
          项目名: {{ project.name }}
        </el-col>
        <el-col :span="16"></el-col>
        <el-col :span="4">
          成员身份: {{ project.role }}
        </el-col>
      </el-row>
    </template>
    <h2 style="margin-bottom: 20px;">项目阶段: {{ project.step }}</h2>
    <el-upload drag class="upload" multiple :http-request="handleUpload" :disabled="!isUploadButtonVisible">
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">
        拖动或者 <em>点击上传文件</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          上传文件小于50MB
        </div>
      </template>
    </el-upload>
    <div class="button-container">
      <el-button type="primary" size="default" @click="goBack" class="custom-button"
        :disabled="!isGroupAvailable || isBackButtonDisabled">
        回到上一阶段
      </el-button>
      <el-button type="primary" size="default" @click="goNext" class="custom-button"
        :disabled="!isGroupAvailable || isNextButtonDisabled">
        {{ nextButtonText }}
      </el-button>
    </div>
  </el-card>

  <!-- 创建小组的对话框 -->
  <el-dialog v-model="dialogVisible" title="创建小组" width="30%" center>
    <el-form :model="createForm" label-width="100px">
      <el-form-item label="小组名称">
        <el-input v-model="createForm.groupName" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>


  <!-- 创建项目的对话框 -->
  <el-dialog v-model="proDialogVisible" title="创建项目" width="30%" center>
    <el-form :model="createForm" label-width="100px">
      <el-form-item label="项目名称">
        <el-input v-model="createForm.projectName" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="proDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFormPro">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style scoped lang="scss">
.el-card {
  width: 100%;
  height: calc(100vh - 90px)
}

.button-container {
  display: flex;
  justify-content: flex-end;
  /* 使按钮靠右 */
  margin-top: 20px;
  /* 可选，根据需要调整上下间距 */
}

/* 新增样式用于带边框的容器 */
.header-button-container {
  border: 1px solid #dfdfdf;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 10px;
}
</style>